import requests
import json
import string
import random
import time

class request_test():
    def env(self, env):
        # 测试环境
        self.test_token = ''
        self.test_url = ''

        # 生产环境
        self.prod_token = ''
        self.prod_url = ''
        if env == 'prod':
            return self.prod_token, self.prod_url
        else:
            return self.test_token,self.test_url

    def date(self, for_num):
        # 测试数据
        self.data = {}

        # 生产数据
        # data = {"id":"241","orgId":"103061","consumptionNo":"103061MU210329000241","contractNo":"","optStatus":"1","chgTmsCnt":"0","businessTypecd":"3","bizopEtpsNm":"测试企业","bizopEtpsNo":"2249S00001","bizopEtpsSccd":"12345678901234567W","passportUsedTypecd":"1","dclData":"","dclTypecd":"1","isChange":"0","businessDeclareNo":"","rmk":"测试数据","masterCuscd":"2249","createTime":"","endTime":"","consumDt":"consumDt_1","produceDt":"produceDt_1","materialUseStatus":[{"id":"2361","pid":"241","createTime":"2021-11-22 21:20:17","optStatus":"1","optUserName":"tester001","optTime":"2021-11-22 21:20:17","remark":"暂存成功","fileName":""},{"id":"261","pid":"241","createTime":"2021-03-29 15:46:26","optStatus":"1","optUserName":"tester001","optTime":"2021-03-29 15:46:26","remark":"暂存成功","fileName":""}],"workOrder":[]}
        # global data
        self.wd = {}
        self.i = 1
        self.consumDt_2 = []
        print("###################准备请求信息###################")
        while self.i <= for_num:
            consumDt_0 = {}
            self.wd.update({"gdsMtno": ''.join(random.sample(string.ascii_letters + string.digits, 8))})
            consumDt_0.update(self.wd)
            self.consumDt_2.append(consumDt_0)
            self.i += 1
        self.data = json.dumps(self.data).replace("wd1", json.dumps(self.consumDt_2)).replace('"[', '[').replace(']"', ']')
        return self.data

    def post_requests(self, for_num, *args):
        status, num, error_num = '1', 1, 1

        while status == '1':
            try:
                headers = {"Content-Type": "application/json", "epToken": "%s" % request_test().env('test')[0]}
                while error_num <= 3:
                    date1 = time.strftime('%Y%m%d%H%M%S')
                    t1 = time.time()
                    response = requests.post(url=request_test().env('test')[1], headers=headers, data=request_test().date(for_num))
                    status = response.json().get("status")
                    ass_value = response.json()
                    t2 = time.time()
                    if status == "1":
                        print("=================单证生成===================")
                        print('第%s次尝试请求成功' % num)
                        id = ass_value.get("map").get('data')
                        print('生成单证id：%s\n 当前单证表体条数：%s' % (id, for_num))
                        error_num = 0
                        break
                    else:
                        print("=================异常反馈===================")
                        print('第%s次请求失败' % num)
                        print('请求时长：%s' % (t2 - t1))
                        if 'token cather user fail' in str(ass_value):
                            print("token失效")
                            break
                        elif status == "0":
                            print('失败返回信息：' + ass_value.get("note"))
                        elif status == '404':
                            print('请求地址错误：' + str(ass_value))
                            break
                        else:
                            print('详细错误信息：' + str(ass_value))
                            print("当前最大支持表体数：%s" % (for_num - 1))
                        error_num += 1
                    num += 1
            except Exception as E:
                print("检查请求信息")
                print(E)
                print(ass_value)
                return False, E, "请求异常"
            if len(args) > 0 and error_num < 3:
                max_num = args[0]
                status = "1"
                if for_num < max_num:
                    for_num += 1
                else:
                    status = '0'
            else:
                status = '0'
            print("###################请求结束###################")
            num += 1

# 输入预期表体数量或预期请求的下限、上限
request_test().post_requests(60, 62)